import java.io.IOException;

import org.apache.commons.codec.binary.Base64;

public class SmtpService extends MailService {
  public SmtpService(String user, String password, String host, int port) {
    super();
    this.user = user;
    this.host = host;
    this.password = password;
    this.port = port;
    // System.out.println(user + " " + host + " " + password + " " + port);
  }

  private void login() {
    sendCommand("EHLO " + host);
    System.out.println(readBufferLines("250 .*"));
    String base64user = new String(Base64.encodeBase64(user.getBytes()));
    String base64password = new String(Base64.encodeBase64(password.getBytes()));
    sendCommand("AUTH LOGIN");
    readBufferLine();
    sendCommand(base64user);
    readBufferLine();
    sendCommand(base64password);
    readBufferLine();

  }

  private void logout() {
    sendCommand("QUIT");
    readBufferLine();
  }

  public void sendMail(String reciepientEmail, String message) {
    try {
      connect(host, port);
      login();

      sendCommand("MAIL FROM: <" + user + ">");
      readBufferLine();
      sendCommand("RCPT TO: <" + reciepientEmail + ">");
      readBufferLine();
      sendCommand("DATA");
      readBufferLine();
      sendCommand(message);
      sendCommand(".");
      readBufferLine();

      logout();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  @Override
  protected void finalize() throws Throwable {
    logout();
    disconnect();
  }



}
